var globalData 					= new Object();
	globalData.loginUrl 		= 'login.php';		//用户登陆接口接口地址
	globalData.getQuestionUrl 	= 'getQuestion.php';	//获取题目接口
jQuery(document).ready(function() {
	
	//	接收url参数 并初始化页面
	var parm = myFun.getUrlParam('parm')
	myFun.initialize( parm );

	//	获取cookie 中上次保存的题目编号
	currentQIdNumber = getCookie( 'currentcurrentQIdNumber' );

	//	进入页面则获取题目信息
	myFun.getQuestionInfo( currentQIdNumber );

    /**************************************以上是业务逻辑的编写********************************************/
	/*选项框选中变色效果*/
	$('.data-form').on('change','input[type=radio]',function(){
		$(".btn-label").removeClass("active");
		$(this).parent(".btn-label").addClass("active");
	});

	$('.data-form').on('change','input[type=checkbox]',function(){
		if( $(this).parent(".btn-label").hasClass("active") ){
			$(this).parent(".btn-label").removeClass("active");
		}else{
			$(this).parent(".btn-label").addClass("active");
		}
	});

	
});
//	题号
var qNumberHtml 		= '<li class="{class}" question-number="{qNumber}" question-sort="{qSort}">{qSort}</li>';
var qNumberFind 		= ['{class}','{qNumber}','{qSort}','{qSort}'];
var qNumberReplace		= new Array();

//	题目标题
var qTitleHtml			= '<h3>题目 {qSort} / {qIdCount} </h3><span class="label label-info pull-left tag-{tagId}">{tagName}</span><p class="title">{title}</p>';
var qTitleFind 			= ['{qSort}','{qIdCount}','{tagId}','{tagName}','{title}'];
var qTitleReplace 		= new Array();

//	答题内容
var qContentHtml		= new Array();
var qContentFind 		= new Array();
var qContentReplace 	= new Array();
	//	单选
	qContentHtml[0]		= '<p><label class="btn btn-default btn-label {class}" ><input type="radio" name="answer" value="{value}" {checked} > {des} </label></p>';
	qContentFind[0] 	= ['{value}','{class}','{checked}','{des}'];
	qContentReplace[0] 	= [];

	//	多选
	qContentHtml[1]		= '<p><label class="btn btn-default btn-label {class}" ><input type="checkbox" name="answer[]" value="{value}" {checked} > {des} </label></p>';
	qContentFind[1] 	= ['{value}','{class}','{checked}','{des}'];
	qContentReplace[1] 	= [];

	//	简单
	qContentHtml[2]		= '<textarea name="answer" placeholder="..." class="form-control {class}" >{value}</textarea>';
	qContentFind[2] 	= ['{value}','{class}','{checked}','{des}'];
	qContentReplace[2] 	= [];

	//	上传
	qContentHtml[3]		= '<input id="upload-file" type="file" multiple class="file {$class}" data-overwrite-initial="false" data-min-file-count="1">';
	qContentFind[3] 	= ['{value}','{class}','{checked}','{des}'];
	qContentReplace[3] 	= [];
var myFun = {
	
	/*获取url参数方法*/
	getUrlParam : function (name) {
	    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
	    var r = window.location.search.substr(1).match(reg);
	    if (r != null) return unescape(r[2]); return null;
	},

	/**接口0 .用户登陆接口*/
	initialize : function ( parm ) {
		parm = $.trim(parm);
		if( parm == '' || parm == null ){
			alert('值不能为空~');
			return false;
		}
		$.ajax({
			type 	: "POST",
			url 	: globalData.loginUrl,
			dataType: "json",
			async	: false,
			success	: function(data){
				if( data.status === 0 ){
					//	计算题目的个数
					data.qIdCount = count(data.qIdList);
					//	把返回数据注册到全局数组中保存
					globalData.init = data;
	    			qIdList = data.qIdList;
	    			myFun.setAnswerNumberList( qIdList );
	    		}else{

	    		}
			}
		});
	},

	/*设置答题卡列表*/
	setAnswerNumberList : function ( qIdList ){
		var html = '';
		var currentQIdNumber = getCookie('currentQIdNumber');
		$.each(qIdList, function(k, v) {
			cla = ''
			if( currentQIdNumber != '' && currentQIdNumber != null ){
				if( currentQIdNumber == v.id ){
					cla = 'active ';
					//	把当前应答题目的编号以及序号保存到cookie中
					setCookie( 'currentQIdNumber' , v.id );
					setCookie( 'qSort' , k );
				}
			}else{
				if( k == 1 ){
					cla = 'active ';
				}
			}

			if( v.answer != '' && v.answer != null ){
				cla += ' over';
			}
			qNumberReplace = [cla,v.id,k,k];
			html += replaceAll( qNumberFind, qNumberReplace, qNumberHtml );
		});
		$(".quesiton-number").html(html);
	},

	/**接口1 .获取题目信息*/
	getQuestionInfo : function ( qNumber ){
		$.ajax({
			type 	: "POST",
			url 	: globalData.getQuestionUrl,
			dataType: "json",
			async	: true,
			success	: function(data){
				if( data.status === 0 ){
					qInfo = data.qInfo;
					if( qInfo._children == null || qInfo._children == '' ){
						qTitleReplace 	= [qInfo.sort, globalData.init.qIdCount, qInfo.tagId, qInfo.tagName, qInfo.title];
						title 			= replaceAll( qTitleFind , qTitleReplace , qTitleHtml );
						$("#question-title").html(title);
						if( ( qInfo.type == 0 || qInfo.type == 1 ) && qInfo.optionList != null ){
							html = '';
							$.each( qInfo.optionList, function(k,v){
								cla = checked = '';
								if( qInfo.answer != null && qInfo.answer != '' && qInfo.answer.indexOf(v.id) !== -1 ){
									cla = 'active';
									checked = 'checked';
								}
								qContentReplace[qInfo.type] = [v.id,cla,checked,v.des];
								html += replaceAll( qContentFind[qInfo.type] , qContentReplace[qInfo.type] , qContentHtml[qInfo.type] );
							});
						}else if( qInfo.type == 3 ){
							html = replaceAll( qContentFind[qInfo.type] , qContentReplace[qInfo.type] , qContentHtml[qInfo.type] );
						}else{
							qContentReplace[qInfo.type] = [qInfo.answer];
							html = replaceAll( qContentFind[qInfo.type] , qContentReplace[qInfo.type] , qContentHtml[qInfo.type] );
						}
						$("#question-content").html(html);
						// 初始化上传插件
						$("#upload-file").fileinput({
					        uploadUrl: 'test.php', // you must set a valid URL here else you will get an error
					        allowedFileExtensions : ['jpg', 'png','gif','php','java','js','html','doc','docx','xls','sql'],
					        overwriteInitial: false,
					        maxFileSize: 100000,
					        maxFilesNum: 100,
					        showUpload: true, 	//是否显示上传按钮
						    // showCaption: false,	//是否显示标题
						    browseClass: "btn btn-primary", //按钮样式    
					        //allowedFileTypes: ['image', 'video', 'flash'],
					        slugCallback: function(filename) {
					            return filename.replace('(', '_').replace(']', '_');
					        },
						});
						//上传完后的回调操作
						$("#upload-file").on("fileuploaded", function(event, data, previewId, index) {
							var form = data.form, files = data.files, extra = data.extra, response = data.response, reader = data.reader;
						});
					}
				}else{

				}
			}
		});
	}

	/**设置题目页面内容*/
}

/*批量替换 find 和 replace 的长度必须一直且搜索值和替换值 一一对应
 * find 要查找的值 		数组格式
 * replace 要替换的值	数组格式
 * string 被搜索替换的字符串
 */
function replaceAll(find,replace,string){
	$.each(find,function(k,v){
		if( replace[k] == '' || replace[k] == null ){
			replace[k] = '';
		}
		string = string.replace(v,replace[k]);
	});
	return string;
}
/* js cookie操作 */
function setCookie(name,value)  //兩個參數，一個是cookie的名字，一個是值
{
    var Days = 5;               //此 cookie 將被保存7天
    var exp  = new Date();      //new Date("December 31, 9998");
    exp.setTime(exp.getTime() + Days*24*60*60*1000);
    document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
}
function getCookie(name)        //取 cookies函數       
{
    var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));
    if(arr != null) return unescape(arr[2]); return null;

}
function delCookie(name)       //刪除 cookie
{
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval=getCookie(name);
    if(cval!=null) document.cookie= name + "="+cval+";expires="+exp.toGMTString();
}

 
/**
 * 取String 或者 object的长度
 * 
 */
function count(o)
{
    var t = typeof o;
    if(t == 'string'){
            return o.length;
    }else if(t == 'object'){
            var n = 0;
            for(var i in o){
                    n++;
            }
            return n;
    }
    return false;
}; 
